<template>
  <div>
    <!-- 顶部栏 -->
    <van-nav-bar title="搜索中心" left-arrow @click-left="$router.go(-1)" />
    <!-- 搜索框 -->
    <van-search
      v-model="value"
      show-action
      autofocus
      shape="round"
      placeholder="请输入搜索关键词"
      @search="onSearch"
      @input="onInput"
      ref="aaa"
    >
      <template #action>
        <div @click="onSearch">搜索</div>
      </template>
    </van-search>
    <!-- 关键字列表 -->
    <van-cell-group inset v-for="(item, index) in keyword" :key="index">
      <van-cell icon="search" @click="$router.push({path:'/searchResult',query:{q:suggestionList[index]}})">
        <template #title>
          <span class="custom-title" v-html="item"></span>
        </template>
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script>
// 搜索关键字联想
import { getSuggestion } from './home.js'

export default {
  name: 'search',
  data () {
    return {
      value: '', // 搜索内容
      suggestionList: [], // 关键字联想
      timeId: null,
    }
  },
  methods: {
    // event事件
    onSearch () {
      this.$router.push({path:'/searchResult',query:{q:this.value}});
    },
    // 输入事件
    onInput () {
      clearTimeout(this.timeId)
      this.timeId = setTimeout(async ()=>{
        if (this.value == '') {
        this.suggestionList = []
        return
      }
      let res = await getSuggestion(this.value)
      this.suggestionList = res.data.data.options
      },500)
    }
  },
  computed: {
    // 关键字变红
    keyword () {
      return this.suggestionList.map(item => {
        let reg = new RegExp(this.value, 'ig')
        return item.replace(
          reg,
          metch => `<span style="color:red">${metch}</span>`
        )
      })
    }
  }
}
</script>

<style></style>
